Skip to content

Conversation

@jsvisa
Copy link
Contributor

@jsvisa jsvisa commented Oct 29, 2025

use the storageKey helper func to reduce the dynamic memory alloc

Signed-off-by: jsvisa <delweng@gmail.com>
@jsvisa jsvisa requested a review from rjl493456442 as a code owner October 29, 2025 03:25
@rjl493456442
Copy link
Member

can you write a benchmark to demonstrate the allocation difference?

@jsvisa
Copy link
Contributor Author

jsvisa commented Nov 4, 2025

@rjl493456442 sorry for the delay,

here is a benchmark script:

package pathdb

import (
	"encoding/binary"
	"testing"

	"github.com/ethereum/go-ethereum/common"
)

const benchDatasetSize = 1024

func benchmarkDataset() ([]common.Hash, []common.Hash) {
	accounts := make([]common.Hash, benchDatasetSize)
	storages := make([]common.Hash, benchDatasetSize)
	for i := 0; i < benchDatasetSize; i++ {
		binary.BigEndian.PutUint64(accounts[i][24:], uint64(i))
		binary.BigEndian.PutUint64(storages[i][24:], uint64(i*17))
	}
	return accounts, storages
}

var (
	benchmarkSink      int
	benchmarkSinkBytes []byte
)

func BenchmarkStorageKey(b *testing.B) {
	accounts, storages := benchmarkDataset()
	mask := benchDatasetSize - 1

	b.Run("storageKey", func(b *testing.B) {
		b.ReportAllocs()
		var sum int
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			idx := i & mask
			accountHash, storageHash := accounts[idx], storages[idx]
			skey := storageKey(accountHash, storageHash)
			key := skey[:]
			sum += int(key[0])
			benchmarkSinkBytes = key
		}
		benchmarkSink = sum
	})

	b.Run("append", func(b *testing.B) {
		b.ReportAllocs()
		var sum int
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			idx := i & mask
			accountHash, storageHash := accounts[idx], storages[idx]
			key := append(accountHash[:], storageHash[:]...)
			sum += int(key[0])
			benchmarkSinkBytes = key
		}
		benchmarkSink = sum
	})
}

The result as below:

goos: linux
goarch: amd64
pkg: github.com/ethereum/go-ethereum/triedb/pathdb
cpu: AMD Ryzen 7 5700G with Radeon Graphics
BenchmarkStorageKey
BenchmarkStorageKey/storageKey
BenchmarkStorageKey/storageKey-16               38741134                32.28 ns/op           64 B/op          1 allocs/op
BenchmarkStorageKey/append
BenchmarkStorageKey/append-16                   24280155                52.87 ns/op           96 B/op          2 allocs/op

Seems the storageKey has a 38.9% per operation improve+, and reduce 1 alloc for each op.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants